﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demos.Problems
{
    public delegate void NuevoMovimiento(int carta1, int carta2);
    public delegate void AnimarBaraja(object sender, EventArgs e);

    public class ObservableQuickSort
    {
        public class InPlaceQuickSorter: Algoritmia.Problems.Sorting.BasicQuickSorter<int>
        {
            public event NuevoMovimiento AñadirMovimiento;
            public event AnimarBaraja ListaOrdenada;
            private List<int> a;

            public List<int> Sort(List<int> a)
            {
                this.a = a;
                _quicksort(0, a.Count);
                ListaOrdenada(this, new EventArgs());
                return a;
            }

            void _quicksort(int p, int r)
            {
                while (r - p > 1)
                {
                    int pivot = a[r - 1];
                    int i = p - 1;
                    for (int j = p; j < r - 1; j++)
                    {
                        if (Comparer<int>.Default.Compare(a[j], pivot) <= 0)
                        {
                            i++;
                            var aux = a[i];
                            a[i] = a[j];
                            a[j] = aux;
                            AñadirMovimiento(i, j);
                        }
                    }
                    var aux2 = a[i + 1];
                    a[i + 1] = a[r - 1];
                    a[r - 1] = aux2;
                    AñadirMovimiento(i + 1, r - 1);

                    int pivot_index = i + 1;
                    if (r - pivot_index < pivot_index - p)
                    {
                        _quicksort(pivot_index, r);
                        r = pivot_index;
                    }
                    else
                    {
                        _quicksort(p, pivot_index);
                        p = pivot_index + 1;
                    }
                }
            }
        }

        
    }
}
